package ziqiangwanqiang.com.boss.channel

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.baidu.speech.EventListener
import com.baidu.speech.EventManager
import com.baidu.speech.EventManagerFactory
import com.baidu.speech.asr.SpeechConstant
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
import io.flutter.view.FlutterView

class BaiduSpeech : EventListener, EventChannel.StreamHandler {
    var methodChannel: MethodChannel
    var eventChannel: EventChannel
    var context: Context
    var activity: Activity
    var methodChannelName: String = "com.ziqiangwanqiang.baidu.speech.method"
    var eventChannelName: String = "com.ziqiangwanqiang.baidu.speech.event"
    var flutterEngine: FlutterEngine
    var asrEvent: EventManager
    lateinit var eventSink: EventChannel.EventSink

    constructor(context: Context, activity: Activity, flutterEngine: FlutterEngine) {
        this.context = context
        this.activity = activity
        this.flutterEngine = flutterEngine

        this.asrEvent = EventManagerFactory.create(this.context, "asr")
        this.asrEvent.registerListener(this)
        
        this.methodChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, methodChannelName)
        this.eventChannel = EventChannel(flutterEngine.dartExecutor.binaryMessenger, eventChannelName)
        this.eventChannel.setStreamHandler(this)

        this.initEvent()
    }

    fun initEvent() {
        methodChannel.setMethodCallHandler { call, result ->

            if (call.method.equals("start")) {
                this.start(result)
            }

            if (call.method.equals("end")) {
                this.end(result)
            }
        }
    }

    fun start(result: MethodChannel.Result) {
        this.initPermission()

        val json = "{\"accept-audio-data\":false,\"disable-punctuation\":false,\"accept-audio-volume\":true,\"pid\":1536}"
        this.asrEvent.send(SpeechConstant.ASR_START, json, null, 0, 0)

        result.success(null)
    }

    fun end(result: MethodChannel.Result?) {
        this.asrEvent.send(SpeechConstant.ASR_STOP, "{}", null, 0, 0)
        result?.success(null)
    }

    override fun onEvent(name: String?, params: String?, data: ByteArray?, offset: Int, length: Int) {
        var map = mapOf(
                "name" to name,
                "params" to params)

        this.eventSink.success(map)
    }

    fun initPermission() {
        //需要的权限列表
        var permissions: Array<String> = arrayOf(Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)

        //检测到的缺失的权限列表
        var toApplyList: MutableList<String> = mutableListOf()

        for (perm in permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this.context, perm)) {
                toApplyList.add(perm)
            }
        }


        if (toApplyList.isNotEmpty()) {
            this.end(null)

            ActivityCompat.requestPermissions(this.activity, toApplyList.toTypedArray(), 123)
        }
    }

    override fun onListen(obj: Any?, eventSink: EventChannel.EventSink?) {
        this.eventSink = eventSink!!
    }

    override fun onCancel(obj: Any?) {
    }
}